﻿using System.ComponentModel;
using System.Reflection;

namespace MyEnum
{
    /// <summary>
    /// 枚举类型帮助类
    /// </summary>
    public static class MyEnumHelper
    {
        /// <summary>
        /// 枚举转字符串
        /// </summary>
        /// <typeparam name="T">枚举对象</typeparam>
        /// <param name="t">枚举实例</param>
        /// <returns>枚举实例名称字符串</returns>
        public static string GetName<T>(this T t)
        {
            string name = Enum.GetName(typeof(T), t);
            return name;
        }

        /// <summary>
        /// 字符串转枚举
        /// </summary>
        /// <typeparam name="T">枚举对象</typeparam>
        /// <param name="name">枚举实例名称字符串</param>
        /// <returns>枚举实例</returns>
        public static T GetT<T>(string name)
        {
            T t = (T)Enum.Parse(typeof(T), name);
            return t;
        }

        /// <summary>
        /// 整型数字（int）转枚举
        /// </summary>
        /// <typeparam name="T">枚举对象</typeparam>
        /// <param name="hashCode">整型数字参数</param>
        /// <returns>枚举实例</returns>
        public static T GetT<T>(int hashCode)
        {
            string name = Enum.GetName(typeof(T), hashCode);
            T t = (T)Enum.Parse(typeof(T), name);
            return t;
        }

        /// <summary>
        /// 根据enum返回描述信息
        /// </summary>
        /// <typeparam name="T">枚举对象</typeparam>
        /// <param name="t">枚举实例</param>
        /// <returns>枚举实例的描述信息</returns>
        public static string GetDescriptionByEnum<T>(this T t)
        {
            Type type = t.GetType();
            MemberInfo[] memberInfos = type.GetMember(t.ToString());
            if (memberInfos != null && memberInfos.Length > 0)
            {
                object[] attrs = memberInfos[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (attrs != null && attrs.Length > 0)
                {
                    return ((DescriptionAttribute)attrs[0]).Description;
                }
            }
            return t.ToString();
        }

        /// <summary>
        /// 根据字符串返回描述信息
        /// </summary>
        /// <typeparam name="T">枚举对象</typeparam>
        /// <param name="str">枚举实例名称字符串</param>
        /// <returns>枚举实例的描述信息</returns>
        public static string GetDescriptionByString<T>(string str)
        {
            return GetDescriptionByEnum(GetT<T>(str));
        }

        /// <summary>
        /// 根据整型返回描述信息
        /// </summary>
        /// <typeparam name="T">枚举对象</typeparam>
        /// <param name="hashCode">枚举实例表示的整型</param>
        /// <returns>枚举实例的描述信息</returns>
        public static string GetDescriptionByInt<T>(int hashCode)
        {
            return GetDescriptionByEnum(GetT<T>(hashCode));
        }
    }
}
